<template>
  <div>
    <!-- 头部 -->
    <div class="login_hander"></div>
    <!-- 表单 -->
    <div class="login-form">
      <van-form @submit="onSubmit">
        <van-field
          v-model="userInfo.account"
          name="用户名"
          label="用户名"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <van-field
          v-model="userInfo.pwd"
          type="password"
          name="密码"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />
        <div style="margin: 16px">
          <van-button round block type="info" native-type="submit"
            >提交</van-button
          >
        </div>
      </van-form>
    </div>
    <div class="register">
      <router-link to='/forgetpassword' tag='a'>忘记密码</router-link><span>|</span><router-link to='/register' tag='a'>点击注册</router-link>

    </div>


  </div>
</template>

<script>
import login from "@/network/login/login.js";
import { ContactList } from 'vant';
export default {
  data() {
    return {
      userInfo:{
        account:"",
        pwd:""
        }
    };
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
  },
  //生命周期 - 挂载完成（访问DOM元素）
  methods: {
    async onSubmit() {
      const {data:res}=await login(this.userInfo);
      if(res.status!=0) return  this.$toast.fail('登录失败');
      this.$toast.success('登录成功');
      this.$store.commit("addUser",{user:res.table,token:res.token})
      localStorage.setItem('userInfo',JSON.stringify(res.table))
      localStorage.setItem('token',res.token)
      this.$router.push('/index')
    },
  },
  async beforeRouteEnter(to, from, next) {
    if(JSON.parse(localStorage.getItem('userInfo'))){
       let userInfo= JSON.parse(localStorage.getItem('userInfo'));
        const {data:res}=await login({account:userInfo.username,pwd:userInfo.pwd});
        if(res.message!="success") return next() 
      localStorage.setItem('userInfo',JSON.stringify(res.table))
      localStorage.setItem('token',res.token)
       next({ name: 'Index' }) 
    }
    else{
       console.log("login")
        next()
    }
  }
};
</script>
<style  lang="less" scoped>
/* @import url(); 引入css类 */
@vw: 0.06667vw;
@vh: 0.03748vw;
.login_hander {
  background-image: url("../assets/loginHander.jpg");
  height: 57.16vw;
  width: 100vw;
  background-size: 100%;
}
.login-form {
  width: 1140 * @vw;
  height: 440 * @vw;

  margin-left: 180 * @vw;
  margin-top: 218 * @vh;

  border-radius: 90 * @vh;
}
.register {
  margin-top: 700 * @vh;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #477bff;
}
.register a {
  font-size: 0.28rem;
  letter-spacing: 0.01rem;
}
.register span {
  padding: 0 0.15rem;
  font-size: 0.18rem;
}
</style>